Appearance
常用注解
后续有空可以更新一下导图内容
组件相关注解
@Controller
用于修饰MVC中controller层的组件,SpringBoot中的组件扫描功能会识别到该注解,并为修饰的类实例化对象,通常与@RequestMapping联用,当SpringMVC获取到请求时会转发到指定路径的方法进行处理。
使用示例
// Controller 调用 Service 和 Repository
@Controller
public class UserController {
private final UserService userService;
@Autowired // 依赖注入
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/user/{id}")
@ResponseBody
public String getUserName(@PathVariable Long id) {
return userService.getUserName(id);
}
}@Service
- 用途:标记类为业务逻辑层,封装复杂的业务逻辑。
- 特点:无特殊功能,但通过语义化分层提高代码可读性。
使用示例
// Service 调用 Repository
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String getUserName(Long userId) {
return userRepository.findUserNameById(userId);
}
}@Repostitory
- 用途:标记类为数据访问层(DAO 层),用于数据库操作。
- 特点:自动处理数据库异常(如将 JDBC 异常转换为 Spring 的
DataAccessException)。
@Component
- 用途:通用的组件注解,用于标记任何层次的组件。
- 特点:当某个类不属于
@Controller、@Service、@Repository时使用。
依赖注入注解
@Autowired
- 作用:自动注入Bean,默认按类型匹配。
- 使用场景:用于字段、构造方法或Setter方法。
会根据对象的类型自动注入依赖对象,默认要求注入对象实例必须存在,可以配置required=false来注入不一定存在的对象。
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
}@Qualifier
- 作用:与
@Autowired配合使用,指定注入的Bean名称。 - 使用场景:当存在多个相同类型的Bean时,用于明确指定注入哪一个。
当同一个对象有多个实例可以注入时,使用@Autowired注解无法进行注入,这时可以使用@Qualifier注解指定实例的名称进行精确注入。
@Autowired
@Qualifier("myServiceA")
private MyService myService;@Resource
- 作用:与
@Autowired类似,但默认按名称匹配。 - 使用场景:适用于需要按名称注入的场景。
默认会根据对象的名称自动注入依赖对象,如果想要根据类型进行注入,可以设置属性为type = UmsAdminService.class。
/**
* @auther macrozheng
* @description 后台用户管理Controller
* @date 2018/4/26
* @github https://github.com/macrozheng
*/
@Controller
@RequestMapping("/admin")
public class UmsAdminController {
@Autowired
@Resource(name = "umsAdminServiceImpl")
private UmsAdminService adminService;
}实例与生命周期相关注解
@Bean
- 作用:在配置类中显式定义 Bean,常用于第三方库组件的注入。
用于修饰方法,标识该方法会创建一个Bean实例,并交给Spring容器来管理。
示例(在 @Configuration 类中):
@Configuration
public class AppConfig {
@Bean // 将方法返回值注册为 Bean
public DataSource dataSource() {
return new HikariDataSource(); // 示例:数据库连接池
}
}@Scope 🌱
@Scope注解用于定义Spring容器中Bean的作用域,即指定Bean实例的创建方式和生命周期。
默认情况下,Spring中的Bean是单例(singleton)模式
作用域的范围有以下几种:
- singleton:单例模式,在Spring容器中该实例唯一,Spring默认的实例模式。
- prototype:原型模式,每次使用实例都将重新创建。
- request:在同一请求中使用相同的实例,不同请求重新创建。
- session:在同一会话中使用相同的实例,不同会话重新创建。
示例:
//本质上下面两种方式都是声明方式
@Component
@Scope("prototype") // 每次注入时创建新实例
public class TaskProcessor {
// 业务逻辑...
}
/**
* @auther macrozheng
* @description RestTemplate相关配置
* @date 2018/4/26
* @github https://github.com/macrozheng
*/
@Configuration
public class RestTemplateConfig {
@Bean
@Scope("singleton")
public RestTemplate restTemplate(){
return new RestTemplate();
}
}@Component 与 @Bean 配置方式的区别
| 特性 | @Component + @Scope | @Bean + @Scope |
|---|---|---|
| 适用场景 | 自己编写的类 | 第三方库的类或需要特殊初始化的类 |
| 定义位置 | 类级别 | 配置类的方法级别 |
| 实例化控制 | Spring自动实例化 | 开发者控制实例化逻辑 |
| 名称指定 | 默认类名首字母小写或通过@Component("name") | 默认方法名或通过@Bean(name="name") |
| 依赖注入 | 通过@Autowired注入 | 可以直接在@Bean方法参数中注入 |
| 条件化配置 | 需要配合@Conditional | 可直接在方法上使用@Conditional |
@Primary
- 作用:当存在多个同类型 Bean 时,标记优先注入的 Bean。
示例:
@Configuration
public class CacheConfig {
@Bean
@Primary // 优先注入
public Cache redisCache() {
return new RedisCache();
}
@Bean
public Cache localCache() {
return new LocalCache();
}
}@PostConstruct
用于修饰方法,当对象实例被创建并且依赖注入完成后执行,可用于对象实例的初始化操作。
Bean 初始化完成后执行的方法(如资源初始化)。
后置处理
@Service
public class FileService {
@PostConstruct
public void init() {
System.out.println("文件服务已启动!");
}
}示例:
/**
* @auther macrozheng
* @description 动态权限数据源,用于获取动态权限规则
* @date 2020/2/7
* @github https://github.com/macrozheng
*/
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private static Map<String, ConfigAttribute> configAttributeMap = null;
@Autowired
private DynamicSecurityService dynamicSecurityService;
@PostConstruct
public void loadDataSource() {
configAttributeMap = dynamicSecurityService.loadDataSource();
}
@PreDestroy
public void clearDataSource() {
configAttributeMap.clear();
configAttributeMap = null;
}
}总结
总结表格
| 注解 | 作用场景 |
|---|---|
@Bean | 显式声明非组件类的 Bean |
@Scope | 控制 Bean 的创建策略(单例/原型) |
@Primary | 解决多个同类型 Bean 的冲突 |
@PostConstruct | Bean 初始化后执行逻辑 |
@PreDestroy | Bean 销毁前执行清理操作 |
@PreDestroy
- 作用:Bean 销毁前执行的方法(如释放资源)。
用于修饰方法,当对象实例将被Spring容器移除时执行,可用于对象实例持有资源的释放。
前置处理
@Service
public class DatabaseConnection {
@PreDestroy
public void close() {
System.out.println("数据库连接已关闭!");
}
}@PostConstruct、@PreDestroy示例
/**
* @auther macrozheng
* @description 动态权限数据源,用于获取动态权限规则
* @date 2020/2/7
* @github https://github.com/macrozheng
*/
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private static Map<String, ConfigAttribute> configAttributeMap = null;
@Autowired
private DynamicSecurityService dynamicSecurityService;
@PostConstruct
public void loadDataSource() {
configAttributeMap = dynamicSecurityService.loadDataSource();
}
@PreDestroy
public void clearDataSource() {
configAttributeMap.clear();
configAttributeMap = null;
}
}SpringMVC 相关注解
@RequestMapping
- 说明:可用于将Web请求路径映射到处理类的方法上,
- 当作用于类上时,可以统一类中所有方法的路由路径,
- 当作用于方法上时,可单独指定方法的路由路径。
method属性可以指定请求的方式,如GET、POST、PUT、DELETE等。
- 作用:映射HTTP请求到控制器方法
- 使用场景:定义请求路径和请求方法。
示例:
@RequestMapping(value = "/api", method = RequestMethod.GET)
public String getData() {
return "Data";
}@RequestBody
表示方法的请求参数为JSON格式,从Body中传入,将自动绑定到方法参数对象中。
@ResponseBody
表示方法将返回JSON格式的数据,会自动将返回的对象转化为JSON数据。
@RequestParam 🌱
用于接收请求参数,可以是如下三种形式:
- query param:GET请求拼接在地址里的参数。
- form data:POST表单提交的参数。
- multipart:文件上传请求的部分参数。
@PathVariable 🌱
用于接收请求路径中的参数,常用于REST风格的API。
相关使用示例
/**
* @auther macrozheng
* @description 后台用户管理Controller
* @date 2018/4/26
* @github https://github.com/macrozheng
*/
@Controller
@RequestMapping("/admin")
public class UmsAdminController {
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam) {
UmsAdmin umsAdmin = adminService.register(umsAdminParam);
if (umsAdmin == null) {
return CommonResult.failed();
}
return CommonResult.success(umsAdmin);
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(adminList));
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<UmsAdmin> getItem(@PathVariable Long id) {
UmsAdmin admin = adminService.getItem(id);
return CommonResult.success(admin);
}
}@RequestPart
用于接收文件上传中的文件参数,通常是multipart/form-data形式传入的参数。
/**
* @auther macrozheng
* @description MinIO对象存储管理Controller
* @date 2019/12/25
* @github https://github.com/macrozheng
*/
@Controller
@RequestMapping("/minio")
public class MinioController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public CommonResult upload(@RequestPart("file") MultipartFile file) {
//省略文件上传操作...
return CommonResult.success(minioUploadDto);
}
}@RestController
- 作用:组合了
@Controller和@ResponseBody,用于定义RESTful Web服务。 - 使用场景:编写API接口时使用。
用于表示controller层的组件,与@Controller注解的不同在于,相当于在每个请求处理方法上都添加了@ResponseBody注解,这些方法都将返回JSON格式数据。
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}@GetMapping
用于表示GET请求方法,等价于@RequestMapping(method = RequestMethod.GET)。
@GetMapping("/users")
public List<User> getUsers() {
return userService.getAllUsers();
}@PostMapping
用于表示POST请求方法,等价于@RequestMapping(method = RequestMethod.POST)。
代码示例
/**
* @auther macrozheng
* @description 后台用户管理Controller
* @date 2018/4/26
* @github https://github.com/macrozheng
*/
@RestController
@RequestMapping("/admin")
public class UmsAdminController {
@PostMapping("/register")
public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam) {
UmsAdmin umsAdmin = adminService.register(umsAdminParam);
if (umsAdmin == null) {
return CommonResult.failed();
}
return CommonResult.success(umsAdmin);
}
@GetMapping("/list")
public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(adminList));
}
}配置相关注解
@Configuration
用于声明一个Java形式的配置类,SpringBoot推荐使用Java配置,在该类中声明的Bean等配置将被SpringBoot的组件扫描功能扫描到。
/**
* @auther macrozheng
* @description MyBatis相关配置
* @date 2019/4/8
* @github https://github.com/macrozheng
*/
@Configuration
@MapperScan({"com.macro.mall.mapper","com.macro.mall.dao"})
public class MyBatisConfig {
}@EnableAutoConfiguration
启用SpringBoot的自动化配置,会根据你在pom.xml添加的依赖和application-dev.yml中的配置自动创建你需要的配置。
@Configuration
@EnableAutoConfiguration
public class AppConfig {
}@ComponentScan 🐒
启用SpringBoot的组件扫描功能,将自动装配和注入指定包下的Bean实例。
@Configuration
@ComponentScan({"xyz.erupt","com.macro.mall.tiny"})
public class EruptConfig {
}@SpringBootApplication
- 作用:标记主启动类,是
@Configuration、@EnableAutoConfiguration和@ComponentScan的组合注解。 - 使用场景:通常用于SpringBoot应用的入口类。
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}@EnableCaching
当添加Spring Data Redis依赖之后,可用该注解开启Spring基于注解的缓存管理功能。
/**
* @auther macrozheng
* @description Redis配置类
* @date 2020/3/2
* @github https://github.com/macrozheng
*/
@EnableCaching
@Configuration
public class RedisConfig extends BaseRedisConfig {
}@Value
用于注入在配置文件中配置好的属性,例如我们可以在application.yml配置如下属性:
jwt:
tokenHeader: Authorization #JWT存储的请求头
secret: mall-admin-secret #JWT加解密使用的密钥
expiration: 604800 #JWT的超期限时间(60*60*24*7)
tokenHead: 'Bearer ' #JWT负载中拿到开头然后在Java类中就可以使用@Value注入并进行使用了。
public class JwtTokenUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
@Value("${jwt.tokenHead}")
private String tokenHead;
}@ConfigurationProperties
用于批量注入外部配置,以对象的形式来导入指定前缀的配置,比如这里我们在application.yml中指定了secure.ignored为前缀的属性:
secure:
ignored:
urls: #安全路径白名单
- /swagger-ui/
- /swagger-resources/**
- /**/v2/api-docs
- /**/*.html
- /**/*.js
- /**/*.css
- /**/*.png
- /**/*.map
- /favicon.ico
- /actuator/**
- /druid/**然后在Java类中定义一个urls属性就可以导入配置文件中的属性了。
/**
* @auther macrozheng
* @description SpringSecurity白名单资源路径配置
* @date 2018/11/5
* @github https://github.com/macrozheng
*/
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "secure.ignored")
public class IgnoreUrlsConfig {
private List<String> urls = new ArrayList<>();
}@Conditional
用于表示当某个条件满足时,该组件或Bean将被Spring容器创建,下面是几个常用的条件注解。
- @ConditionalOnBean:当某个Bean存在时,配置生效。
- @ConditionalOnMissingBean:当某个Bean不存在时,配置生效。
- @ConditionalOnClass:当某个类在Classpath存在时,配置生效。
- @ConditionalOnMissingClass:当某个类在Classpath不存在时,配置生效。
/**
* @auther macrozheng
* @description Jackson相关配置,配置json不返回null的字段
* @date 2018/8/2
* @github https://github.com/macrozheng
*/
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
}数据库事务相关注解
@EnableTransactionManagement
启用Spring基于注解的事务管理功能,需要和@Configuration注解一起使用。
/**
* @auther macrozheng
* @description MyBatis相关配置
* @date 2019/4/8
* @github https://github.com/macrozheng
*/
@Configuration
@EnableTransactionManagement
@MapperScan({"com.macro.mall.mapper","com.macro.mall.dao"})
public class MyBatisConfig {
}@Transactional
表示方法和类需要开启事务,当作用与类上时,类中所有方法均会开启事务,当作用于方法上时,方法开启事务,方法上的注解无法被子类所继承。
- 作用:声明事务管理,确保方法内的数据库操作要么全部成功,要么全部回滚。
- 使用场景:用于需要事务管理的业务方法。
/**
* @auther macrozheng
* @description 前台订单管理Service
* @date 2018/8/30
* @github https://github.com/macrozheng
*/
public interface OmsPortalOrderService {
/**
* 根据提交信息生成订单
*/
@Transactional
Map<String, Object> generateOrder(OrderParam orderParam);
}SpringSecurity 相关注解
@EnableWebSecurity
启用SpringSecurity的Web功能。
@EnableGlobalMethodSecurity
启用SpringSecurity基于方法的安全功能,当我们使用@PreAuthorize修饰接口方法时,需要有对应权限的用户才能访问。
使用配置示例:
/**
* @auther macrozheng
* @description SpringSecurity配置
* @date 2019/10/8
* @github https://github.com/macrozheng
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig{
}全局异常处理注解
@ControllerAdvice
常与@ExceptionHandler注解一起使用,用于捕获全局异常,能作用于所有controller中。
@ExceptionHandler
修饰方法时,表示该方法为处理全局异常的方法。
全局异常处理示例
/**
* @auther macrozheng
* @description 全局异常处理
* @date 2020/2/27
* @github https://github.com/macrozheng
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(value = ApiException.class)
public CommonResult handle(ApiException e) {
if (e.getErrorCode() != null) {
return CommonResult.failed(e.getErrorCode());
}
return CommonResult.failed(e.getMessage());
}
}AOP 相关注解
@Aspect
用于定义切面,切面是通知和切点的结合,定义了何时、何地应用通知功能。
@Before
表示前置通知(Before),通知方法会在目标方法调用之前执行,通知描述了切面要完成的工作以及何时执行。
@After
表示后置通知(After),通知方法会在目标方法返回或抛出异常后执行。
@AfterReturning
表示返回通知(AfterReturning),通知方法会在目标方法返回后执行。
@AfterThrowing
表示异常通知(AfterThrowing),通知方法会在目标方法返回后执行。
@Around
表示环绕通知(Around),通知方法会将目标方法封装起来,在目标方法调用之前和之后执行自定义的行为。
@Pointcut
定义切点表达式,定义了通知功能被应用的范围。
@Order
用于定义组件的执行顺序,在AOP中指的是切面的执行顺序,value属性越低优先级越高。
AOP 相关示例
/**
* @auther macrozheng
* @description 统一日志处理切面
* @date 2018/4/26
* @github https://github.com/macrozheng
*/
@Aspect
@Component
@Order(1)
public class WebLogAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);
@Pointcut("execution(public * com.macro.mall.tiny.controller.*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
}
@AfterReturning(value = "webLog()", returning = "ret")
public void doAfterReturning(Object ret) throws Throwable {
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
WebLog webLog = new WebLog();
//省略日志处理操作...
Object result = joinPoint.proceed();
LOGGER.info("{}", JSONUtil.parse(webLog));
return result;
}
}测试相关注解
@SpringBootTest
用于指定测试类启用Spring Boot Test功能,默认会提供Mock环境。
@Test
指定方法为测试方法。
测试示例
/**
* @auther macrozheng
* @description JUnit基本测试
* @date 2022/10/11
* @github https://github.com/macrozheng
*/
@SpringBootTest
public class FirstTest {
@Test
public void test() {
int a=1;
Assertions.assertEquals(1,a);
}
}